package com.itheima.auth.intergration.advice;

import com.itheima.auth.intergration.entity.MyOauthTokenDTO;
import com.itheima.common.exception.enums.ResponseEnum;
import com.itheima.common.threadlocal.UserHolder;
import com.itheima.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class AuthTokenAspect {

    /// @Around是可以改变controller返回值的
    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        Result result = new Result();
        Object proceed = pjp.proceed();
        if (proceed != null) {
            ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>)proceed;
            OAuth2AccessToken body = responseEntity.getBody();
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                MyOauthTokenDTO myOauthTokenDTO = new MyOauthTokenDTO();
                myOauthTokenDTO.setOauth2AccessToken(body);
                myOauthTokenDTO.setUser(UserHolder.getUserInfo());
                result.setCode(ResponseEnum.SUCCESS.getCode());
                result.setSuccess(true);
                result.setMessage(ResponseEnum.SUCCESS.getMessage());
                result.setData(myOauthTokenDTO);
            } else {
                log.error("error:{}", responseEntity.getStatusCode().toString());
                result.setCode(ResponseEnum.ERROR.getCode());
                result.setSuccess(false);
                result.setMessage("获取Token失败");
            }
        }
        return ResponseEntity.status(200).body(result);
    }
}
